package com.guigu.dealservice.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.common.utils.R;
import com.guigu.dealservice.dto.Equipment;
import com.guigu.dealservice.entity.UserCollection;
import com.guigu.dealservice.feign.MyEquipmentFeign;
import com.guigu.dealservice.service.UserCollectionService;
import com.guigu.dealservice.vo.UserCollectionEquipmentVoPC;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 收藏表（存储用户收藏的设备信息） 前端控制器
 * </p>
 *
 * @author ysp
 * @since 2025-10-10
 */
@RestController
@RequestMapping("/dealservice/collection")
public class UserCollectionController {
    @Autowired
    private UserCollectionService userCollectionService;


    @Autowired
    private MyEquipmentFeign myEquipmentFeign;

    /**
     * 添加收藏
     * @param userId
     * @param equipmentId
     * @return
     */
    @PostMapping("/addCollection/{userId}/{equipmentId}")
    public R addCollection(@PathVariable Long userId,@PathVariable Long equipmentId) {
        String s = userCollectionService.addCollection(userId, equipmentId);
        return R.ok().data("result",s);
    }

    /**
     * 删除收藏
     * @param userId
     * @param equipmentId
     * @return
     */
    @DeleteMapping("/deleteCollection/{userId}/{equipmentId}")
    public R deleteCollection(@PathVariable Long userId,@PathVariable Long equipmentId) {
        String s = userCollectionService.deleteCollection(userId, equipmentId);
        return R.ok().data("result",s);
    }


    /**
     * 前台-根据登录的用户分页带条件查询收藏的设备信息
     * */
    @PostMapping("/PageQueryCollectionEquipmentByUserId/{userId}/{pageNum}/{pageSize}")
    public R PageQueryCollectionEquipmentByUserId(@PathVariable("userId") Integer userId,
                                                  @PathVariable("pageNum") Integer pageNum,
                                                  @PathVariable("pageSize") Integer pageSize, @RequestBody UserCollectionEquipmentVoPC userCollectionEquipmentVoPC) {

        QueryWrapper<UserCollection> userCollectionQueryWrapper = new QueryWrapper<>();
        userCollectionQueryWrapper.eq("user_id", userId);

        // 1. 先查询所有符合条件的收藏记录
        List<UserCollection> allUserCollections = userCollectionService.list(userCollectionQueryWrapper);

        // 2. 处理设备信息并过滤有效数据
        List<UserCollection> allValidCollections = new ArrayList<>();
        for (UserCollection userCollection : allUserCollections) {
            //远程调用
            Equipment equipmentDto = myEquipmentFeign.queryEquipmentAndImageAndType(
                    userCollection.getEquipmentId(), userCollectionEquipmentVoPC);

            if (equipmentDto != null) {
                userCollection.setEquipment(equipmentDto);
                allValidCollections.add(userCollection);
            }
        }

        // 3. 手动分页（添加边界检查）
        int total = allValidCollections.size();
        int startIndex = (pageNum - 1) * pageSize;

        // 边界检查：确保 startIndex 不超过总数据量
        if (startIndex >= total) {
            // 如果起始索引超出范围，返回空列表
            return R.ok()
                    .data("userCollectionList", new ArrayList<>())
                    .data("total", total);
        }

        int endIndex = Math.min(startIndex + pageSize, total);
        List<UserCollection> resultList = allValidCollections.subList(startIndex, endIndex);

        return R.ok()
                .data("userCollectionList", resultList)
                .data("total", total);
    }


    /**
     * 前台-根据主键id删除掉收藏的设备消息
     * */
    @DeleteMapping("/deleteCollectionEquipmentByCoId/{id}")
    public R deleteCollectionEquipmentByCoId(@PathVariable("id") Integer id){

        boolean b = userCollectionService.removeById(id);

        if (b==true)
            return R.ok().code(20000).message("删除成功").data("success", true);
        return R.error().code(20001).message("删除失败").data("success", false);
    }


    /**
     * 前台-根据用户id查询收藏的设备信息
     * */
    @GetMapping("/selectCollectionEquipmentByUserId/{userId}/{equipmentId}")
        public R selectCollectionEquipmentByUserId(@PathVariable("userId") Long userId,@PathVariable("equipmentId") Long equipmentId){

        QueryWrapper<UserCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("equipment_id", equipmentId);
        boolean isCollected = userCollectionService.count(queryWrapper) > 0;
        return R.ok().data("isCollected", isCollected);

    }

    /**
     * 前台-我要买-点击收藏
     * */
    @PostMapping("/addCollectionEquipmentByUserId")
    public R addCollectionEquipmentByUserId(@RequestBody UserCollection userCollection){
        QueryWrapper<UserCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userCollection.getUserId())
                .eq("equipment_id", userCollection.getEquipmentId());
        UserCollection userCollection1 = userCollectionService.getOne(queryWrapper);
        //判断没有就添加
        if (userCollection1== null){
            userCollection.setCollectionTime(LocalDateTime.now());
            boolean b = userCollectionService.save(userCollection);
            if (b)
                return R.ok().code(20000).message("收藏成功").data("success", true);
            return R.error().code(20001).message("收藏失败").data("success", false);
        }else {
            boolean b = userCollectionService.removeById(userCollection1);
            if (b)
                return R.ok().code(20000).message("取消收藏成功").data("success", true);
                return R.error().code(20001).message("取消收藏失败").data("success", false);
        }
    }

}
